package cn.itcast.es;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class ES_Data_CRUD {

    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("192.168.20.129", 9200, "http"))
        );

        // 创建索引请求对象
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("user").id("1006");
        User user = new User();
        user.setSex("男");
        user.setName("张三");
        user.setAge(18);

        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        indexRequest.source(userJson, XContentType.JSON);
        // 创建es索引数据/修改全量数据
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println("获取响应:"+response.getResult());

        // --------------------------------------分割线---------------------------------------------


        // 修改索引数据部分数据
        UpdateRequest updateRequest = new UpdateRequest();
        // 指定索引和id
        updateRequest.index("user").id("1003");
        // 指定修改的数据
        updateRequest.doc(XContentType.JSON,"age", "20");
        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.printf("获取响应:"+update.getResult());

        // --------------------------------------分割线---------------------------------------------

        // 删除索引数据
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.index("user").id("1006");

        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println("获取响应:"+delete.getResult());

        // --------------------------------------分割线---------------------------------------------

        // 查询索引数据
        GetRequest getRequest = new GetRequest();
        getRequest.index("user").id("1001");

        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);

        System.out.println("获取响应:"+getResponse.getSourceAsString());
        client.close();

    }
}
